<?php

namespace Biz\service\wiki;

use Biz\model\brandIndex\BrandMsg;
use Biz\model\store\StoreCustomCategoryWiki;
use Biz\model\store\StoreMsg;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\model\wiki\WikiBasicLog as mWikiBasicLog;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Biz\service\brand\Brand;
use Biz\service\BrandIndex;
use Biz\service\Store\StoreBasicService;
use Biz\service\Store\StoreBusinessService;
use Biz\service\wiki\WikiBasic as sWikiBasic;
use Biz\tools\RealUrl;
use Doraemon\cache\Queue;
use Doraemon\model\Category as mCategory;
use Doraemon\service\Category as sCategory;
use Doraemon\tools\BlockType;
use Doraemon\tools\ImgUrl;
use Exception;
use Medoo\Medoo;

class AdmWikiBasic
{
    const DEFAULT_HAOHAOZHU_UID = 11941;

    /**
     * 审核列表
     * @param $where
     * @return array
     */
    public static function admGetAuditWikiList($where)
    {
        $list = [];
        $where['wiki.is_official'] = 1;//过滤掉没有官方wiki的商品
        $where['GROUP'] = ['wiki_basic.id'];
        $select = [
            'wiki_basic.id',
            'wiki_basic.brand_id',
            'wiki_basic.store_id',
            'wiki_basic.title',
            'wiki_basic.series',
            'wiki_basic.style',
            'wiki_basic.material',
            'wiki_basic.space',
            'wiki_basic.cover_img',
            'wiki_basic.imgs',
            'wiki_basic.category_id',
            'wiki_basic.second_category_id',
            'wiki_basic.third_category_id',
            'wiki_basic.four_category_id',
            'wiki_basic.last_category_id',
            'wiki_basic.basic_state',
            'wiki_basic.addtime',
            'wiki_basic.edittime',
        ];

        $wikiBasicArr = mWikiBasic::select(['[><]wiki' => ['id' => 'basic_id']], $select, $where);
        $wikiBasicList = [];
        foreach ($wikiBasicArr as $row) {
            $info = mWikiBasic::formatInfo($row);
            $wikiBasicList[] = $info;
        }

        if ($wikiBasicList) {
            $brandIds = array_column($wikiBasicList, 'brand_id');
            $storeIdArr = array_column($wikiBasicList, 'store_id');
            $brandList = Brand::getBrandsInfoByIds($brandIds);
            $storeList = StoreBasicService::getStoreInfoByIdArr($storeIdArr);
            unset($where['LIMIT']);
            unset($where['ORDER']);
            unset($where['GROUP']);
            $totalRes = mWikiBasic::get(['[><]wiki' => ['id' => 'basic_id']],
                ['count' => Medoo::raw("count(DISTINCT(wiki_basic.id))")], $where);
            $total = ($totalRes && isset($totalRes['count'])) ? $totalRes['count'] : 0;
            $basicIds = array_column($wikiBasicList, 'id');
            $categoryIds = [];
            foreach ($wikiBasicList as $k => $row) {
                $categoryIds[] = $row['category_id'];
                $categoryIds[] = $row['second_category_id'];
                $categoryIds[] = $row['third_category_id'];
                $categoryIds[] = $row['four_category_id'];
                $wikiBasicList[$k]['cover_img'] = !empty($row['cover_img']) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                    $row['cover_img'], ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
            }
            if ($basicIds) {
                //wiki列表
                $wikiSpuArr = mWiki::selectByWhere(['basic_id' => $basicIds, 'is_official' => 1]);
                $wikiSpuList = [];
                foreach ($wikiSpuArr as $row) {
                    $wikiSpuList[$row['basic_id']][] = $row;
                    $categoryIds[] = $row['category_id'];
                    $categoryIds[] = $row['second_category_id'];
                    $categoryIds[] = $row['third_category_id'];
                    $categoryIds[] = $row['four_category_id'];
                }
                $categoryIds = array_unique(array_filter($categoryIds));
                $categoryList = [];
                if ($categoryIds) {
                    $categoryList = mCategory::getCategoryList($categoryIds);
                    $categoryList = array_column($categoryList, null, 'id');
                }
                $logWhere['operate_type'] = mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT;
                $logWhere['operate_value'] = mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE;
                $logWhere['log_state'] = mWikiBasicLog::STATE_NORMAL;
                $logWhere['basic_id'] = $basicIds;
                $editAuditBasicIds = mWikiBasicLog::selectByWhere($logWhere, 'basic_id');
                foreach ($wikiBasicList as $row) {
                    if (in_array($row['id'], $editAuditBasicIds)) {
                        $row['basic_state'] = mWikiBasic::STATE_EDIT_AUDIT;
                    }
                    $row['category_name'] = isset($categoryList[$row['category_id']]) ? $categoryList[$row['category_id']]['cate_name'] : '';
                    $row['second_category_name'] = isset($categoryList[$row['second_category_id']]) ? $categoryList[$row['second_category_id']]['cate_name'] : '';
                    $row['third_category_name'] = isset($categoryList[$row['third_category_id']]) ? $categoryList[$row['third_category_id']]['cate_name'] : '';
                    $row['four_category_name'] = isset($categoryList[$row['four_category_id']]) ? $categoryList[$row['four_category_id']]['cate_name'] : '';
                    $row['basic_state_desc'] = mWikiBasic::admAuditStateDesc($row['basic_state']);
                    $row['brand_name'] = isset($brandList[$row['brand_id']]) ? $brandList[$row['brand_id']]['brand_name'] : '';
                    $row['brand_type'] = isset($brandList[$row['brand_id']]) ? $brandList[$row['brand_id']]['brand_type'] : 0;
                    $row['brand_logo'] = isset($brandList[$row['brand_id']]) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                        $brandList[$row['brand_id']]['logo'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE) : Brand::BRAND_DEFAULT_LOGO;

                    //门店信息
                    $row['store_name'] = $storeList[$row['store_id']]['name'] ?? '';
                    $row['store_logo'] = $storeList[$row['store_id']]['logo_url'] ?? '';


                    $row['spu_title'] = '';
                    $row['spu_list'] = [];
                    if (isset($wikiSpuList[$row['id']])) {
                        foreach ($wikiSpuList[$row['id']] as $spuInfo) {
                            if (empty($row['cover_img']) && $spuInfo['is_default']) {
                                $row['cover_img'] = $spuInfo['cover_img'];
                            }
                            if ($spuInfo['is_default']) {
                                $row['spu_title'] = $spuInfo['title'];
                            }
                            $row['spu_list'][] = [
                                'id' => $spuInfo['id'],
                                'cover_img' => $spuInfo['cover_img'],
                                'url' => RealUrl::formatLink($spuInfo['channel_spu_id'], $spuInfo['channel_type'],
                                    $spuInfo['channel_jump_params'], $spuInfo['channel_shop_id']),
                                'channel' => mWiki::CHANNEL_MAP[$spuInfo['channel']],
                                'title' => $spuInfo['title'],
                                'channel_spu_id' => $spuInfo['channel_spu_id'],
                                'channel_spu_status' => $spuInfo['channel_spu_status'],
                                'is_default' => $spuInfo['is_default'],
                                'status' => $spuInfo['status'],
                            ];
                        }
                    }
                    $list[] = $row;
                }
            }
        }

        return ['list' => $list, 'total' => $total];
    }


    /**
     * 审核列表
     * @param $where
     * @return array
     */
    public static function admGetEditAuditWikiList($where)
    {
        $list = [];
        $total = 0;
        $where['operate_type'] = mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT;
        $where['operate_value'] = mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE;
        $where['log_state'] = mWikiBasicLog::STATE_NORMAL;
        //获取wiki_basic_log列表
        $logList = mWikiBasicLog::selectByWhere($where);
        $basicIds = array_column($logList, 'basic_id');
        $basicIds = array_unique($basicIds);
        //获取wiki_basic 列表
        $wikiBasicList = mWikiBasic::selectByWhere(['id' => $basicIds, 'basic_state[!]' => mWikiBasic::STATE_DEL]);
        if ($wikiBasicList) {
            $new = array_column($wikiBasicList, 'cover_img', 'id');
            $brandIds = array_column($wikiBasicList, 'brand_id');
            $brandList = Brand::getBrandsInfoByIds($brandIds);
            $storeIdArr = array_column($wikiBasicList, 'store_id');
            $storeArr = StoreBasicService::getStoreInfoByIdArr($storeIdArr);
            $total = mWikiBasic::selectCountWhere(['id' => $basicIds, 'basic_state[!]' => mWikiBasic::STATE_DEL]);
            $categoryIds = [];
            foreach ($wikiBasicList as $row) {
                $categoryIds[] = $row['category_id'];
                $categoryIds[] = $row['second_category_id'];
                $categoryIds[] = $row['third_category_id'];
                $categoryIds[] = $row['four_category_id'];
            }
            foreach ($logList as $k => $val) {
                if (in_array($val['basic_id'], $basicIds) && !empty($new[$val['basic_id']])) {
                    $logList[$k]['cover_img'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $new[$val['basic_id']],
                        ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG);
                } else {
                    $logList[$k]['cover_img'] = '';
                }
            }
            $spuIds = [];
            $auditBasicList = [];
            $categoryIds = [];
            foreach ($logList as $row) {
                $operateData = json_decode($row['operate_data'], true);
                if ($operateData) {
                    $auditBasicList[$row['basic_id']] = [
                        'basic_id' => $row['basic_id'],
                        'basic_data' => $operateData ? $operateData['basic'] : [],
                        'spu' => $operateData ? $operateData['spu'] : [],
                        'cover_img' => $row['cover_img'],
                    ];
                    if ($operateData && $operateData['basic']) {
                        $categoryIds[] = $operateData['basic']['category_id'];
                        $categoryIds[] = $operateData['basic']['second_category_id'];
                        $categoryIds[] = $operateData['basic']['third_category_id'];
                        $categoryIds[] = $operateData['basic']['four_category_id'];
                    }
                    foreach ($operateData['spu'] as $spuRow) {
                        $spuIds[] = $spuRow['id'];
                    }
                }
            }
            $spuIds = array_filter(array_unique($spuIds));
            $wikiSpuArr = mWiki::selectByWhere(['id' => $spuIds]);
            $wikiSpuList = [];
            if ($wikiSpuArr) {
                foreach ($wikiSpuArr as $row) {
                    $wikiSpuList[$row['id']] = $row;
                    $categoryIds[] = $row['category_id'];
                    $categoryIds[] = $row['second_category_id'];
                    $categoryIds[] = $row['third_category_id'];
                    $categoryIds[] = $row['four_category_id'];
                }
            }
            $categoryIds = array_unique(array_filter($categoryIds));
            $categoryList = [];
            if ($categoryIds) {
                $categoryList = mCategory::getCategoryList($categoryIds);
                $categoryList = array_column($categoryList, null, 'id');
            }
            foreach ($auditBasicList as $basicId => $row) {
                $basicInfo = $row['basic_data'];
                $basicInfo['id'] = $basicId;
                $basicInfo['cover_img'] = isset($row['cover_img']) ? $row['cover_img'] : '';
                $basicInfo['category_name'] = isset($categoryList[$basicInfo['category_id']]) ? $categoryList[$basicInfo['category_id']]['cate_name'] : '';
                $basicInfo['second_category_name'] = isset($categoryList[$basicInfo['second_category_id']]) ? $categoryList[$basicInfo['second_category_id']]['cate_name'] : '';
                $basicInfo['third_category_name'] = isset($categoryList[$basicInfo['third_category_id']]) ? $categoryList[$basicInfo['third_category_id']]['cate_name'] : '';
                $basicInfo['four_category_name'] = isset($categoryList[$basicInfo['four_category_id']]) ? $categoryList[$basicInfo['four_category_id']]['cate_name'] : '';
                $basicInfo['basic_state_desc'] = mWikiBasic::admAuditStateDesc($basicInfo['basic_state']);
                $basicInfo['brand_name'] = isset($brandList[$basicInfo['brand_id']]) ? $brandList[$basicInfo['brand_id']]['brand_name'] : '';
                $basicInfo['brand_type'] = isset($brandList[$basicInfo['brand_id']]) ? $brandList[$basicInfo['brand_id']]['brand_type'] : 0;
                $basicInfo['brand_logo'] = isset($brandList[$basicInfo['brand_id']]) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                    $brandList[$basicInfo['brand_id']]['logo'],
                    ImgUrl::IMAGE_SIZE_SQ_PHONE) : Brand::BRAND_DEFAULT_LOGO;

                //门店新增 显示信息
                $basicInfo['store_name'] = $storeArr[$basicInfo['store_id']]['name'] ?? '';
                $basicInfo['store_logo'] = $storeArr[$basicInfo['store_id']]['logo_url'] ?? '';
                $basicInfo['brand_id'] = $basicInfo['brand_id'] ?? 0;
                $basicInfo['store_id'] = $basicInfo['store_id'] ?? 0;
                foreach ($row['spu'] as $spuData) {
                    $spuInfo = isset($wikiSpuList[$spuData['id']]) ? $wikiSpuList[$spuData['id']] : [];
                    if ($spuInfo) {
                        if (empty($basicInfo['cover_img'])) {
                            $basicInfo['cover_img'] = $spuInfo['cover_img'];
                        }
                        if ($spuData['is_default']) {
//                            $basicInfo['cover_img'] = $spuInfo['cover_img'];
                            $basicInfo['spu_title'] = $spuInfo['title'];
                        }
                        $basicInfo['spu_list'][] = [
                            'id' => $spuInfo['id'],
                            'cover_img' => $spuInfo['cover_img'],
                            'url' => RealUrl::formatLink($spuInfo['channel_spu_id'], $spuInfo['channel_type'],
                                $spuInfo['channel_jump_params'], $spuInfo['channel_shop_id']),
                            'channel' => mWiki::CHANNEL_MAP[$spuInfo['channel']],
                            'title' => $spuInfo['title'],
                            'channel_spu_id' => $spuInfo['channel_spu_id'],
                            'is_default' => $spuData['is_default'],
                            'status' => $spuInfo['status'],
                        ];
                    }
                }
                $list[] = $basicInfo;
            }
        }

        return ['list' => $list, 'total' => $total];
    }


    /**
     * 审核wiki
     * @param $id
     * @param $state
     * @param $adminUid
     * @param $reason
     * @throws \Exception
     */
    public static function audit($id, $state, $adminUid, $reason)
    {
        $info = mWikiBasic::getByWhere(['id' => $id]);
        $spuList = mWiki::selectByWhere(['basic_id' => $id, 'is_official' => 1]);
        $defaultSpuId = 0;
        foreach ($spuList as $row) {
            $defaultSpuId = $row['id'];
            if ($row['is_default']) {
                $defaultSpuId = $row['id'];
                break;
            }
        }
        if (empty($info)) {
            throw  new Exception('不存在的wiki');
        }
        $brandId = $info['brand_id'];
        $brandInfo = $brandId ? Brand::getBrandsInfoByIds([$brandId]) : [];
        $brandInfo = isset($brandInfo[$brandId]) ? $brandInfo[$brandId] : [];
        $brandUid = $brandInfo ? $brandInfo['uid'] : 0;
        $storeId = $info['store_id'];
        $storeInfo = $storeId ? StoreBasicService::getStoreInfoByIdArr([$storeId]) : [];
        $storeUid = $storeInfo[$storeId]['uid'] ?? 0;
        if (!$brandId && !$storeUid) {
            throw new Exception('非品牌/门店的wiki不能操作');
        }
        switch ($state) {
            case mWikiBasic::STATE_NOT_PASS:
                if (!$reason) {
                    throw new Exception('请输入不通过审核的原因');
                }
//                if (!in_array($info['basic_state'], [mWikiBasic::STATE_NORMAL, mWikiBasic::STATE_EDIT_AUDIT])) {
//                    throw new \Exception('待审核的wiki才能操作审核不通过');
//                }
                mWikiBasic::updateData(['basic_state' => $state], ['id' => $id]);
                self::addLog($id, $state, ['basic_state' => $state, 'reason' => $reason],
                    ['basic_state' => $info['basic_state']], $adminUid);
                if ($brandUid > 0) {
                    $msg = '你提交的（' . $info['title'] . '）未通过审核，原因为：' . $reason;
                    Queue::insertQueue('queue/Sysmsg/Send',
                        [
                            'msgCode' => 0,
                            'to_uid' => $brandUid,
                            'msgParams' => [
                                'from_uid' => self::DEFAULT_HAOHAOZHU_UID,
                                'title' => '',
                                'img' => '',
                                'link' => '',
                                'detail' => $msg,
                            ],
                        ], Queue::QUEUE_DORAEMON
                    );
                    BrandIndex::writeMsg($brandId, BrandMsg::MSG_TYPE_OVER, BrandMsg::MSG_SOURCE_SHOP, $msg,
                        BlockType::TYPE_WIKI_BASIC, $defaultSpuId);
                }
                if ($storeUid > 0) {
                    $storeMsg = '您添加的商品 ' . $info['title'] . ' 未通过审核，原因为：' . $reason;
                    StoreBusinessService::writeMsg($storeId, StoreMsg::MSG_TYPE_NO_PASS,
                        StoreMsg::MSG_SOURCE_WIKI_AUDIT, $storeMsg, BlockType::TYPE_WIKI, $defaultSpuId);
                }
                break;
            case mWikiBasic::STATE_PASS:
                if (!in_array($info['basic_state'],
                    [mWikiBasic::STATE_NORMAL, mWikiBasic::STATE_EDIT_AUDIT, mWikiBasic::STATE_NOT_PASS])) {
                    throw new Exception('当前wiki的状态不能操作审核通过');
                }
                $state = mWikiBasic::STATE_ONLINE;
                mWikiBasic::updateData(['basic_state' => $state], ['id' => $id]);
                mWiki::updateData(['status' => mWiki::STATUS_CHECKED], ['basic_id' => $id, 'status' => mWiki::STATUS_WAIT_CHECK, 'is_official' => 1]);
                self::addLog($id, $state, ['basic_state' => $state], ['basic_state' => $info['basic_state']],
                    $adminUid);
                if ($brandUid > 0) {
                    $msg = '您添加的商品 ' . $info['title'] . ' 已通过审核并已生效';
                    Queue::insertQueue('queue/Sysmsg/Send',
                        [
                            'msgCode' => 0,
                            'to_uid' => $brandUid,
                            'msgParams' => [
                                'from_uid' => self::DEFAULT_HAOHAOZHU_UID,
                                'title' => '',
                                'img' => '',
                                'link' => '',
                                'detail' => $msg,
                            ],
                        ], Queue::QUEUE_DORAEMON
                    );
                    BrandIndex::writeMsg($brandId, BrandMsg::MSG_TYPE_PASS, BrandMsg::MSG_SOURCE_SHOP, $msg,
                        BlockType::TYPE_WIKI_BASIC, $defaultSpuId);
                }
                if ($storeUid > 0) {
                    $storeMsg = '您添加的商品 ' . $info['title'] . ' 已通过审核并已生效';
                    StoreBusinessService::writeMsg($storeId, StoreMsg::MSG_TYPE_PASS,
                        StoreMsg::MSG_SOURCE_WIKI_AUDIT, $storeMsg, BlockType::TYPE_WIKI, $defaultSpuId);
                }
                break;
        }
        if ($id) {
            sWikiBasic::afterChangeBasic([$id], $brandId, $storeId);
        }
    }

    /**
     * wiki basic 插入日志
     * @param $basicId basic id
     * @param $operateValue 操作的值（比如审核通过，则为审核通过的状态值）
     * @param array $operateData 操作的数据
     * @param array $sourceData 操作前的原数据
     * @param int $adminId 管理员id
     */
    public static function addLog($basicId, $operateValue, array $operateData, array $sourceData, $adminId = 0)
    {
        $data = [
            'basic_id' => $basicId,
            'operate_type' => mWikiBasicLog::OPERATE_TYPE_AUDIT,
            'operate_value' => $operateValue,
            'operate_data' => json_encode($operateData, JSON_UNESCAPED_UNICODE),
            'operate_source_data' => json_encode($sourceData, JSON_UNESCAPED_UNICODE),
            'admin_id' => $adminId,
        ];
        mWikiBasicLog::insertData($data);
    }

    /**
     * 审核通过-多条审核
     * @param array $ids
     * @param $adminId
     * @throws \Exception
     */
    public static function audits(array $ids, $adminId)
    {
        foreach ($ids as $id) {
            $info = mWikiBasic::getByWhere(['id' => $id]); //基础表wiki
            $spuList = mWiki::selectByWhere(['basic_id' => $id, 'is_official' => 1]); // 商品表wiki

            $defaultSpuId = 0;
            foreach ($spuList as $row) {
                $defaultSpuId = $row['id'];
                if ($row['is_default']) {
                    $defaultSpuId = $row['id'];
                    break;
                }
            }
            if (empty($info)) {
                throw  new Exception("ID:" . $id . '不存在的wiki');
            }
            $brandId = $info['brand_id'];
            $brandInfo = $brandId ? Brand::getBrandsInfoByIds([$brandId]) : [];
            $brandInfo = isset($brandInfo[$brandId]) ? $brandInfo[$brandId] : [];
            $brandUid = $brandInfo ? $brandInfo['uid'] : 0;
            $state = mWikiBasic::STATE_ONLINE;
            mWikiBasic::updateData(['basic_state' => $state], ['id' => $id]);
            mWiki::updateData(['status' => mWiki::STATUS_CHECKED], ['basic_id' => $id, 'status' => mWiki::STATUS_WAIT_CHECK, 'is_official' => 1]);
            self::addLog($id, $state, ['basic_state' => $state], ['basic_state' => $info['basic_state']], $adminId);
            if ($brandUid > 0) {
                $msg = '您添加的商品 ' . $info['title'] . ' 已通过审核并已生效';
                Queue::insertQueue('queue/Sysmsg/Send',
                    [
                        'msgCode' => 0,
                        'to_uid' => $brandUid,
                        'msgParams' => [
                            'from_uid' => self::DEFAULT_HAOHAOZHU_UID,
                            'title' => '',
                            'img' => '',
                            'link' => '',
                            'detail' => $msg,
                        ],
                    ], Queue::QUEUE_DORAEMON
                );
                BrandIndex::writeMsg($brandId, BrandMsg::MSG_TYPE_PASS, BrandMsg::MSG_SOURCE_SHOP, $msg,
                    BlockType::TYPE_WIKI_BASIC, $defaultSpuId);
            }

            sWikiBasic::afterChangeBasic([$id], $brandId);

        }

    }

    /**
     * @param $id
     * @param $state
     * @param $adminUid
     * @param $reason
     * @throws \Exception
     */
    public static function editAuditWiki($id, $state, $adminUid, $reason)
    {
        $info = mWikiBasic::getByWhere(['id' => $id]);
        $spuList = mWiki::selectByWhere(['basic_id' => $id, 'is_official' => 1]);
        $defaultSpuId = 0;
        foreach ($spuList as $row) {
            $defaultSpuId = $row['id'];
            if ($row['is_default']) {
                $defaultSpuId = $row['id'];
                break;
            }
        }
        if (empty($info) || !$id) {
            throw  new Exception('不存在的wiki');
        }
        $logInfo = mWikiBasicLog::getByWhere([
            'basic_id' => $id,
            'log_state' => mWikiBasicLog::STATE_NORMAL,
            'operate_type' => mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT,
            'operate_value' => mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE,
        ]);
        if (empty($logInfo)) {
            throw  new Exception('不存在的编辑待审核wiki');
        }
        $brandId = $info['brand_id'];
        $brandInfo = $brandId ? Brand::getBrandsInfoByIds([$brandId]) : [];
        $brandUid = $brandInfo[$brandId]['uid'] ?? 0;
        $storeId = $info['store_id'];
        $storeInfo = $storeId ? StoreBasicService::getStoreInfoByIdArr([$storeId]) : [];
        $storeUid = $storeInfo[$storeId]['uid'] ?? 0;
        if (!$brandId && !$storeUid) {
            throw new Exception('非品牌/门店的wiki不能操作');
        }
        switch ($state) {
            case mWikiBasic::STATE_NOT_PASS:
                if (!$reason) {
                    throw new Exception('请输入不通过审核的原因');
                }
                mWikiBasicLog::updateData(['log_state' => mWikiBasicLog::STATE_DEL],
                    ['basic_id' => $id, 'id' => $logInfo['id']]);
                self::addLog($id, $state, ['basic_state' => $state, 'reason' => $reason, 'log_id' => $logInfo['id']],
                    ['basic_state' => $info['basic_state']], $adminUid);
                if ($brandUid > 0) {
                    $msg = '你提交的（' . $info['title'] . '）未通过审核，原因为：' . $reason;
                    Queue::insertQueue('queue/Sysmsg/Send',
                        [
                            'msgCode' => 0,
                            'to_uid' => $brandUid,
                            'msgParams' => [
                                'from_uid' => self::DEFAULT_HAOHAOZHU_UID,
                                'title' => '',
                                'img' => '',
                                'link' => '',
                                'detail' => $msg,
                            ],
                        ], Queue::QUEUE_DORAEMON
                    );
                    BrandIndex::writeMsg($brandId, BrandMsg::MSG_TYPE_OVER, BrandMsg::MSG_SOURCE_SHOP, $msg,
                        BlockType::TYPE_WIKI_BASIC, $defaultSpuId);
                }
                if ($storeUid > 0) {
                    $storeMsg = '您添加的商品 ' . $info['title'] . ' 未通过审核，原因为：' . $reason;
                    StoreBusinessService::writeMsg($storeId, StoreMsg::MSG_TYPE_NO_PASS,
                        StoreMsg::MSG_SOURCE_WIKI_AUDIT, $storeMsg, BlockType::TYPE_WIKI, $defaultSpuId);
                }
                break;
            case mWikiBasic::STATE_PASS:
                self::passEditAuditWiki($info, $logInfo);
                mWikiBasicLog::updateData(['log_state' => mWikiBasicLog::STATE_PASS],
                    ['basic_id' => $id, 'id' => $logInfo['id']]);
                $state = mWikiBasic::STATE_ONLINE;
                self::addLog($id, $state, ['basic_state' => $state, 'log_id' => $logInfo['id']],
                    ['basic_state' => $info['basic_state']], $adminUid);
                if ($brandUid > 0) {
                    $msg = '您添加的商品 ' . $info['title'] . ' 已通过审核并已生效';
                    Queue::insertQueue('queue/Sysmsg/Send',
                        [
                            'msgCode' => 0,
                            'to_uid' => $brandUid,
                            'msgParams' => [
                                'from_uid' => self::DEFAULT_HAOHAOZHU_UID,
                                'title' => '',
                                'img' => '',
                                'link' => '',
                                'detail' => $msg,
                            ],
                        ], Queue::QUEUE_DORAEMON
                    );
                    BrandIndex::writeMsg($brandId, BrandMsg::MSG_TYPE_PASS, BrandMsg::MSG_SOURCE_SHOP, $msg,
                        BlockType::TYPE_WIKI_BASIC, $defaultSpuId);
                }
                if ($storeUid > 0) {
                    $storeMsg = '您添加的商品 ' . $info['title'] . ' 已通过审核并已生效';
                    StoreBusinessService::writeMsg($storeId, StoreMsg::MSG_TYPE_PASS,
                        StoreMsg::MSG_SOURCE_WIKI_AUDIT, $storeMsg, BlockType::TYPE_WIKI, $defaultSpuId);
                }
                break;
        }
    }

    /**
     * 编辑待审核，审核通过
     * @param $basicInfo
     * @param $logInfo
     * @throws \Exception
     */
    private static function passEditAuditWiki($basicInfo, $logInfo)
    {
        $operateData = $logInfo['operate_data'] ?? '';
        $operateData = json_decode($operateData, true);
        if (!$operateData || !$operateData['basic']) {
            throw  new Exception('没有要审核的wiki信息');
        }
        $brandId = $basicInfo['brand_id'];
        $storeId = $basicInfo['store_id'];
        $basicId = $basicInfo['id'];
        $dataBasic = $operateData['basic'];
        $dataSpuArr = $operateData['spu'];
        $wikiBasicData = [
            'brand_id' => $brandId,
            'store_id' => $storeId,
            'title' => $dataBasic['title'],
            'series' => $dataBasic['series'],
            'style' => $dataBasic['style'],
            'material' => $dataBasic['material'],
            'space' => $dataBasic['space'],
            'category_id' => $dataBasic['category_id'],
            'second_category_id' => $dataBasic['second_category_id'],
            'third_category_id' => $dataBasic['third_category_id'],
            'four_category_id' => $dataBasic['four_category_id'],
            'last_category_id' => $dataBasic['last_category_id'],
            'basic_state' => mWikiBasic::STATE_ONLINE,
            'wiki_type' => $dataBasic['wiki_type'] ?? mWikiBasic::ON_LINE, //1线上商品 2虚拟商品
        ];

        $spuIds = array_column($dataSpuArr, 'id');

        $mWikiData = mWiki::selectByWhere(['id' => $spuIds]);
        $wikiSpuList = !empty($mWikiData) ? $mWikiData : [];
        $wikiSpuIds = array_column($wikiSpuList, 'id');
        $wikiSpuIds = !empty($wikiSpuIds) ? $wikiSpuIds : [];
        $wikiSpuList = array_column($wikiSpuList, null, 'id');
        if ($brandId > 0) {
            foreach ($wikiSpuList as $id => $row) {
                if ($row['brand_id'] && $row['brand_id'] != $brandId) {
                    throw new Exception('ID为 ' . $row['channel_spu_id'] . ' 的商品已被其他品牌收录，请核验后重新添加');
                }
            }
        }
        mWikiBasic::updateData($wikiBasicData, ['id' => $basicId]);

        if ($brandId > 0) {
            $mWikiDataBasic = mWiki::selectByWhere(['brand_id' => $brandId, 'basic_id' => $basicId], '*');
        }
        if ($storeId > 0) {
            $mWikiDataBasic = mWiki::selectByWhere(['store_id' => $storeId, 'basic_id' => $basicId], '*');
        }
        $allWikiSpuList = !empty($mWikiDataBasic) ? $mWikiDataBasic : [];
        $allWikiSpuIds = array_column($allWikiSpuList, 'id');
        $allWikiSpuIds = !empty($allWikiSpuIds) ? $allWikiSpuIds : [];
        $cancelWikiSpuIds = array_diff($allWikiSpuIds, $wikiSpuIds);
        if ($cancelWikiSpuIds) {
            foreach ($allWikiSpuList as $row) {
                //取消商品和wiki的关联，新建一个wiki basic
                if (in_array($row['id'], $cancelWikiSpuIds)) {
                    if ($row['channel'] == mWiki::CHANNEL_NOTHING) {
                        mWiki::updateData(['status' => mWiki::STATUS_DEL], ['id' => $row['id']]);//虚拟商品，直接删除
                    } else {//不在归宿当前basic，故解除当前关联关系，新增一个basic
                        $newData = [
                            'title' => $row['title'],
                            'brand_id' => 0,
                            'category_id' => $row['category_id'],
                            'second_category_id' => $row['second_category_id'],
                            'third_category_id' => $row['third_category_id'],
                            'four_category_id' => $row['four_category_id'],
                            'last_category_id' => $row['last_category_id'],
                            'basic_state' => mWikiBasic::STATE_NORMAL,
                        ];
                        $newBasicId = mWikiBasic::insertData($newData);
                        mWiki::updateData([
                            'brand_id' => 0,
                            'basic_id' => $newBasicId,
                            'is_default' => 1,
                            'is_official' => 0,
                        ], ['basic_id' => $basicId, 'id' => $row['id'], 'brand_id' => $brandId]);
                    }
                }
            }
        }
        foreach ($dataSpuArr as $row) {
            $isDefault = isset($row['is_default']) ? $row['is_default'] : 0;
            $wikiSpuData = [
                'basic_id' => $basicId,
                'channel' => $row['channel'],
                'channel_type' => clsWiki::getChannelType($row['channel']),
                'channel_spu_id' => $row['channel_spu_id'],
                'brand_id' => $brandId,
                'category_id' => $wikiBasicData['category_id'],
                'second_category_id' => $wikiBasicData['second_category_id'],
                'third_category_id' => $wikiBasicData['third_category_id'],
                'four_category_id' => $wikiBasicData['four_category_id'],
                'last_category_id' => $wikiBasicData['last_category_id'],
                'is_default' => $isDefault,
                'is_official' => 1,
            ];

            //价格修改
            if($row['min_price'] && $row['min_price'] ){
                $wikiSpuData['min_price'] = $row['min_price'];
            }

            if(isset($row['max_price']) && $row['max_price'] ){
                $wikiSpuData['max_price'] = $row['max_price'];
            }

            if (isset($wikiSpuList[$row['id']])) {
                if ($wikiSpuList[$row['id']]['status'] == mWiki::STATUS_DEL) {
                    $wikiSpuData['status'] = mWiki::STATUS_NORMAL;
                }
                mWiki::updateData($wikiSpuData,
                    ['channel' => $row['channel'], 'channel_spu_id' => $row['channel_spu_id']]);
            } else {
                $wikiSpuData['source_basic_id'] = $basicId;
                $wikiId = mWiki::insertData($wikiSpuData);
                if ($wikiId) {
                    $itemId = $wikiSpuData['channel_spu_id'];
                    $type = $wikiSpuData['channel_type'];
                    $channelJumpParams = isset($wikiSpuData['channel_jump_params']) ? $wikiSpuData['channel_jump_params'] : '';
                    $channelShopId = isset($wikiSpuData['channel_shop_id']) ? $wikiSpuData['channel_shop_id'] : 0;
                    $url = RealUrl::formatLink($itemId, $type, $channelJumpParams, $channelShopId);
                    if ($url) {
                        //添加抓取wiki任务
                        Wiki::addGetWikiSpuTask($url);
                    }
                }
            }
        }
        if ($storeId > 0) {
            StoreCustomCategoryWiki::addData(0, $storeId, $basicId);
        }
        sWikiBasic::afterChangeBasic([$basicId], $brandId, $storeId);
    }

    /**
     * @desc 获取子类目id映射名称
     * @param $parentId int 父类目id
     * @return array
     */
    public static function admGetChildCategoryMap($parentId = 0)
    {
        $rs = sCategory::getChildCategory($parentId);

        return empty($rs) ? [] : array_column($rs, 'cate_name', 'id');
    }

    /**
     * 获取wiki_basic cover_img imgs
     * @param $id
     * @param string $field
     * @return array
     */
    public static function getImgs($id, $field = '*')
    {
        return mWikiBasic::getInfosById($id, $field);
    }

    /**
     * 更新数据
     * @param array $data
     * @param $where
     * @return bool
     */
    public static function upInfo(array $data, $where)
    {
        return mWikiBasic::updateData($data, $where);
    }
}
